import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import sk.upjs.gursky.bplustree.BPTree;

public class KlastrovanyBPT {

    private BPTree<Kluc, Zaznam> tree;
   
    public KlastrovanyBPT() throws Exception {
        tree = new BPTree<Kluc, Zaznam>(Zaznam.class, new File("indexBP2.idx"));
        List<Zaznam> zaznamy = new ArrayList<Zaznam>();
       
        RandomAccessFile raf = new RandomAccessFile("clovek.tab", "r");
        FileChannel channel = raf.getChannel();
        ByteBuffer buffer = ByteBuffer.allocateDirect(4096);
       
        long dlzka = raf.length();
        long pocetStranok = dlzka / 4096;
       
        for (int i = 0; i < pocetStranok; i++) {
            buffer.rewind();
            channel.read(buffer);
            buffer.rewind();
            int pocetZaznamov = buffer.getInt();
           
            for (int j = 0; j < pocetZaznamov; j++) {
                Zaznam zaznam = new Zaznam();
                zaznam.load(buffer);
                zaznamy.add(zaznam);
                //System.out.println(zaznam);
            }           
        }
        channel.close();
        raf.close();
       
        Collections.sort(zaznamy);
        tree.openAndBatchUpdate(zaznamy.iterator(), zaznamy.size());
    }
   
    public List<Zaznam> rozsahovyDopyt(Kluc od, Kluc po) {
        return tree.rozsahovyDopyt(od, po);
    }
   
    public void close() {
        try {
        	tree.close();
        } catch (IOException e){
            e.printStackTrace();
        }
    }
   
    public static void main(String[] args) throws Exception {
        KlastrovanyBPT kl = new KlastrovanyBPT();
        
        kl.tree.resetCountIOs();
        
        long time = System.nanoTime();
        List<Zaznam> vysledok = kl.rozsahovyDopyt(new Kluc("ayh"), new Kluc("99999999"));
        time = System.nanoTime() - time;
        System.out.println(vysledok);
        System.out.println(time);
        
        System.out.println("Klastrovany index - pocet I/O: " + kl.tree.getCountIOs());
        kl.close();       
    }   
}